import Ability from '@ohos.app.ability.UIAbility';
import Window from '@ohos.window';
import deviceInfo from '@ohos.deviceInfo';

import { initInfo, userGrantPermission, getAppWindowSize, getScreenOrientation, DistributedManager } from "@ohos/utilslibrary";
let log = initInfo('MainAbility');
const BUNDLENAME = "com.ohos.demandplayer";
const ABILITYNAME = "MainAbility";
let transferManager = DistributedManager.getInstance();

export default class MainAbility extends Ability {
    changeWant(want){
        globalThis.abilityWant = want
        globalThis.isTransferData = false;
        globalThis.startByLauncher = false;
        let sessionId = ""
        let videoIndex = 0;
        let url = "";
        let currentTime = 0;
        let videoList = [];
        // 分布式流转
        if(want.parameters.startBy && want.parameters.startBy == BUNDLENAME){
            globalThis.isTransferData = true;
            if(want.parameters.stopTransfer){
                globalThis.abilityContext.terminateSelfWithResult({resultCode:1}).then(()=>{
                    log('terminateSelfWithResult success');
                })
                return;
            }
            videoIndex = want.parameters.videoIndex;
            currentTime = want.parameters.currentTime;
            url = want.parameters.url;
            videoList = JSON.parse(want.parameters.videoList);
            globalThis.currentTime = currentTime;
            globalThis.videoIndex = videoIndex;
            AppStorage.SetOrCreate<Array<any>>('video_list', videoList)
        }

        // 沉浸式点播
        if(want.parameters.startByLauncher){
            globalThis.startByLauncher = true;
            videoIndex = want.parameters.videoIndex;
            let urlList = JSON.parse(want.parameters.videoList);
            globalThis.currentTime = 0;
            globalThis.videoIndex = videoIndex;

            urlList.forEach(t=>{
                videoList.push({
                    uri:t.uri || "",
                    url:t.url,
                    type: 'http',
                    displayName: t.name,
                    resolution: '1080P',
                    resolutions:[]
                })
            })
            url = videoList[videoIndex].url;

            AppStorage.SetOrCreate<Array<any>>('video_list', videoList)
        }

        AppStorage.SetOrCreate('sessionId', sessionId);

    }

    onCreate(want, launchParam) {
        log('Ability onCreate');
        globalThis.abilityContext = this.context;
        globalThis.deviceType = 'default';
        let softwareModel = deviceInfo.softwareModel.toLowerCase();
//        log(`softwareModel: ${softwareModel}`)
        if(softwareModel.startsWith('tv')){
            globalThis.deviceType = 'tv';
        }

        globalThis.transferManager = transferManager;

        globalThis.videoIndex = 0;
        this.changeWant(want);
    }

    onDestroy() {
        log('Ability onDestroy');
        if(transferManager){
            transferManager.release();
        }
    }

    onWindowStageCreate(windowStage: Window.WindowStage) {
        console.log('onWindowStageCreate');
        // @ts-ignore
        globalThis.abilityContext = this.context;

        windowStage.getMainWindow().then((win)=>{
            globalThis.mainWindow = win;
            win.setKeepScreenOn(true).then(()=>{
//                log(`win.setKeepScreenOn true`);
            })

            getScreenOrientation().then(res=>{
                globalThis.orientation = res;
            })

            getAppWindowSize(win).then((data)=>{
                log('getAppWindowSize data:' + JSON.stringify(data));
                AppStorage.SetOrCreate<number>('screen_px_w',data.pageW)
                AppStorage.SetOrCreate<number>('screen_px_h',data.pageH)
                AppStorage.SetOrCreate<number>('screen_lpx_w',data.width)
                AppStorage.SetOrCreate<number>('screen_lpx_h',data.height)
                AppStorage.SetOrCreate<number>('screen_dpi',data.dpi)
                AppStorage.SetOrCreate<number>('screen_lpi',data.lpi)
                globalThis.lpi = data.lpi;
                globalThis.lpiPx = (num:number) => {
                    return globalThis.lpi *num + 'px';
                };

                let loadContentUrl = 'pages/index';
                if(globalThis.isTransferData || globalThis.startByLauncher){
                    loadContentUrl = 'pages/videoPlayer';
                }

                windowStage.loadContent(loadContentUrl, (err, data) => {
                    if (err.code) {
                        log('Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                        return;
                    }
                    if(transferManager){
                        transferManager.startScan();
                    }
                    if(globalThis.deviceType == 'default'){
                        userGrantPermission(globalThis.abilityContext, {
                            permissions: [
                                {
                                    "name": "ohos.permission.READ_MEDIA"
                                },
                                {
                                    "name": "ohos.permission.WRITE_MEDIA"
                                },
                                {
                                    "name": "ohos.permission.MEDIA_LOCATION"
                                },
                                {
                                    "name": "ohos.permission.READ_IMAGEVIDEO"
                                },
                                {
                                    "name": "ohos.permission.READ_AUDIO"
                                },
                                {
                                    "name": "ohos.permission.READ_DOCUMENT"
                                },
                                {
                                    "name": "ohos.permission.DISTRIBUTED_DATASYNC"
                                },
                                {
                                    "name": "ohos.permission.MICROPHONE"
                                }
                            ]
                        })
                    }
                })
            })
        })
    }

    onWindowStageDestroy() {
        // Main window is destroyed, release UI related resources
        log('Ability onWindowStageDestroy');
    }

    onForeground() {
        // Ability has brought to foreground
        log('Ability onForeground');
    }

    onBackground() {
        // Ability has back to background
        log('Ability onBackground');
    }

    onNewWant(want) {
        log('Ability onNewWant');
        if(want.parameters.startBy && want.parameters.startBy == BUNDLENAME){
            if(want.parameters.stopTransfer){
                globalThis.abilityContext.terminateSelfWithResult({resultCode:1, want:want}).then(()=>{
                    log('terminateSelfWithResult success');
                })
                return;
            }
            this.changeWant(want);
            if(globalThis.isTransferData){
                globalThis.mainWindow.loadContent('pages/videoPlayer', (err, data) => {
                    if (err.code) {
                        log('Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
                        return;
                    }
                    log(`windowStage.loadContent Data: ${JSON.stringify(data)}`);
                });
            }
        }
    }
}
